/**
 * 客户资源录入脚本支持
 */
var key = null;
var clientKey = null;
var studentKey = null;
var reserveKey = null;
var modifydata = null;
var studentdata = null;

//页面载入初始化
$( "body" ).ready( function( e )
{
	try
	{
		if( typeof ( eval( "init" ) ) == "function" )
			eval( "init();" );
	}
	catch( e )
	{
	}

	// 初始化
	button_bind();
	client_detailed( $( "#tbl_client" ), false );
	init_table_sh_click( $( "#tbl_reception" ) );
	init_table_sh_click( $( "#student_test_list" ) );
	// 初始化选择
	if( !empty( clientKey ) && !empty( modifydata ) )
	{
		clientSelectedHandler( modifydata );
		setReception( modifydata );
	}

} );

//--------------------------------------------------------------------------
//
//	consultant_client.php
//
//--------------------------------------------------------------------------

function button_bind()
{
	$( "#tbl_reserve" ).find( "tr:first > th" ).css( "cursor", "pointer" );
	$( "#tbl_reserve" ).find( "tr:first > th" ).click( name_row_click );
	$( "#tbl_student_temp" ).hide();

	$( "#btn_detailed" ).click( function( e )
	{
		e.stopPropagation();

		var show = $( "#tbl_client" ).find( "tr[rel='hide']" ).eq( 0 ).visible();
		client_detailed( $( "#tbl_client" ), !show );
	} );
	
	$("#btnStudent").click(function(e){
		exec_student(e);
	});
	
	$("#btnAddTracking").click(function(e){
		exec_tracking(e);
	});
	
}

function exec_student(e){
	e.stopPropagation();
	clientKey = $("#clientkey").val();
	if( empty( clientKey ) )
	{
		infopad.err( "请先指定目标客户，再添加跟踪情况。" );
		return;
	}

	var id = parent.create_model(contextPath+"/index/consultant_client.htm?keyname="+clientKey+"&type=1", "编辑预约信息", null, 8000 );
	parent.mask_layer.index( 7999 );
	parent.open_model( id ,true);
	
}

function exec_tracking(e)
{
	e.stopPropagation();
	clientKey = $("#clientkey").val();;
	if( empty( clientKey ) )
	{
		infopad.err( "请先指定目标客户，再添加跟踪情况。" );
		return;
	}
	var id = parent.create_model(contextPath+"/index/consultant_client.htm?keyname="+clientKey+"&type=1", "编辑预约信息", null, 8000 );
	parent.mask_layer.index( 7999 );
	parent.open_model( id ,true);

}

function init_table_sh_click( tbl )
{
	var th = tbl.find( "tr[class=fields] th" );

	th.css( "cursor", "pointer" );
	th.bind( "click", function()
	{
		var trs = $( this ).parent().parent().find( "tr[class!=fields]" );
		trs.eq( 0 ).css( "display" ) == "none" ? trs.show() : trs.hide();
	} );
}
function copy_student_temp( id )
{
	var temp = $( "#tbl_student_temp" );
	var container = $( "#student_test_list" );

	container.append( temp.clone( true ) );

	var tbl = container.find( "table:last" );
	tbl.attr( "id", id );

	// 学员表单头部点击事件
	tbl.find( "tr:first > th" ).click( name_row_click );
	tbl.find( "tr:first > th" ).css( "cursor", "pointer" );
	tbl.find( "tr:first > th" ).trigger( "click" );

	// 测评项目调查表隐藏、显示
	tbl.find( "[rel='btnShowVote']" ).hide();
	tbl.find( "[rel='btnArrow']" ).add( tbl.find( "[rel='btnShowVote']" ) ).click( function( e )
	{
		var vote = tbl.find( "[rel='result'] > div" );
		if( vote.visible() )
		{
			vote.hide();
			tbl.find( "[rel='btnShowVote']" ).show();
		}
		else
		{
			vote.show();
			tbl.find( "[rel='btnShowVote']" ).hide();
		}
	} );
	tbl.find( "[rel='btnArrow']" ).trigger( "click" );

}

function client_detailed( tar, visible )
{
	if( visible )
		tar.find( "tr[rel='hide']" ).show();
	else
		tar.find( "tr[rel='hide']" ).hide();

	setTableRowBackColor( tar );
}

//--------------------------------------------------------------------------
//
//	数据提交
//
//--------------------------------------------------------------------------

function clientSelectedHandler( data )
{
	if( typeof ( data ) == "undefined" )
		return;

	// 有效用户检测
	if( data.invalid == 1 || data.source == "cru0943rdrf2" || data.category == "510a4qf1i57p" )
	{
		infopad.err( "无效、未知、广告推销类型的客户无须添加学员资料。" );
		return;
	}

	setClientData( data );
	setReception( null );
	setStudent( null );

	if( clientKey != null )
	{
		request_reserve( clientKey, reserveKey );
		request_student( clientKey );
	}
}

function setClientData( data )
{
	// 客户资料
	if( typeof ( data ) == "object" && data.nickname )
	{
		if( empty( data.client ) )
			clientKey = data.key;
		else
			clientKey = data.client;

		$( "#nickname" ).html(
				data.nickname
						+ ( data.invalid == 1 ? "<em class='caption'>（无效客户）</em>"
								: "<em class='valid'>（有效客户）</em>" ) );
		$( "#category" ).html( shtml( data.categoryns ) );
		$( "#source" ).html( shtml( data.sourcens ) );
		$( "#keyword" ).html( shtml( data.keyword ) );
		$( "#address" ).html( data.province + " " + data.city + " " + data.address );
		$( "#phone" ).html( shtml( data.phone ) );
		$( "#email" ).html( shtml( data.email ) );
		$( "#qq" ).html( shtml( data.qq ) );
		$( "#ip" ).html( shtml( data.ip ) );
	}
	else
	{
		clientKey = null;

		$( "#nickname" ).html( "&nbsp;" );
		$( "#category" ).html( "&nbsp;" );
		$( "#source" ).html( "&nbsp;" );
		$( "#address" ).html( "&nbsp;" );
		$( "#keyword" ).html( "&nbsp;" );
		$( "#address" ).html( "&nbsp;" );
		$( "#phone" ).html( "&nbsp;" );
		$( "#email" ).html( "&nbsp;" );
		$( "#qq" ).html( "&nbsp;" );
		$( "#ip" ).html( "&nbsp;" );
	}
}

function setReception( d )
{
	if( !empty( d ) )
	{
		key = d.key;

		$( "#worth" ).val( d.worth );
		$( "#feature" ).html( d.feature );

		$( "#btnSelectBox" ).hide();
		$( "#rdate" ).replaceWith( "<span class=\"stress unit hand\" id=\"rdate\">" + d.date + "</span>" );
		$( "#ruser" ).replaceWith(
				"<span class=\"stress unit hand\" id=\"ruser\">" + d.receptionns + "</span>" );
		$( "#region" ).replaceWith(
				"<span class=\"stress unit hand\" id=\"region\">" + d.regionns + "</span>" );
	}
}

function setStudent( d )
{
	if( !empty( d ) )
	{
		for( var key in d )
		{
			var v = d[ key ];
			var tbl = $( "#" + key );
			set_student_data( tbl, v );
		}
	}
	else
	{
		$( "#student_test_list > table" ).each( function( idx )
		{
			var tbl = $( this );
			tbl.find( "[rel='testuser'] select" ).val( "" );
			tbl.find( "div[rel='price']" ).html( "" );
			tbl.find( "div[rel='moneylog']" ).html( "" );
			tbl.find( "div[rel='reason']" ).html( "" );
			tbl.find( "div[rel='remark']" ).html( "" );

			tbl.find( "[rel='result'] > div :radio" ).prop( "checked", false );
			tbl.find( "[rel='result'] > div :text" ).val( "" );
		} );
	}
}

/**
 * 设置指定表单的学员接待数据
 */
function set_student_data( tbl, d )
{
	tbl.find( "[rel='testuser']" ).html( "<span class=\"stress unit hand\">" + d.testuser + "</span>" );
	tbl.find( "div[rel='price']" ).html( d.price );
	tbl.find( "div[rel='moneylog']" ).html( d.moneylog );
	tbl.find( "div[rel='reason']" ).html( d.reason );
	tbl.find( "div[rel='remark']" ).html( d.remark );

	// 设置当前选择的测评完成情况选择
	selects = ( !empty( d.result ) ? d.result : "" ).split( "," );
	var ps = tbl.find( "[rel='result'] > div" ).find( "p[rel^='TR_']" );

	// 过滤兼容没有选择的旧记录
	if( selects.length == ps.length )
	{
		ps.each( function( id )
		{
			var val = selects[ id ];
			if( val )
			{
				var txt = "";

				if( val.indexOf( ":" ) != -1 )
				{
					var tmp = val.split( ":" );
					val = tmp[ 0 ];
					txt = tmp[ 1 ];
				}

				$( this ).find( ":radio[value=" + val + "]" ).prop( "checked", true );

				if( $( this ).find( "input[name^='TXT_']" ).length > 0 )
					$( this ).find( "input[name^='TXT_']" ).val( txt );
			}
		} );
	}
}

function shtml( val )
{
	if( empty( val ) )
		return "<em class='caption'>未填写</em>";
	else if( val == '--' )
		return "<em class='caption'>禁止查看</em>";
	return val;
}

function request_reserve( key, rkey )
{
	submitter.post( "reserve_search.php", {
		key: key,
		rkey: rkey
	}, function( d )
	{
		if( d.err == 0 )
		{
			var size = parseInt( d[ 'size' ] );

			if( size == 1 )
			{
				empty_reserve();
				setReserveData( d );
			}
			else
			{
				nodata_reserve( '未搜索到<span class="confirmed unit hand" id="state">待确认</span>的预约记录。' );
			}
		}
		else
		{
			infopad.err( d.msg );
		}
	}, "json" );
}

function request_student( key )
{
	submitter.post( "student_search.php", {
		key: key
	}, function( d )
	{
		if( d.err == 0 )
		{
			$( "#studentlst" ).empty();

			var size = parseInt( d[ 'size' ] );

			for( var i = 0; i < size; i++ )
			{
				var v = d[ i ];
				setNewStudent( v );
			}

			// 若已读取学员接待数据则设置
			if( !empty( clientKey ) && !empty( studentdata ) )
			{
				setStudent( studentdata );
			}
		}
		else
		{
			infopad.err( d.msg );
		}
	}, "json" );
}

function setNewStudent( d )
{
	// 克隆表单
	copy_student_temp( d.key );

	// 设置学员基本数据	
	var tbl = $( "#" + d.key );
	tbl.show();

	// 学员情况包含学员资料和接待情况（来源于tg_student及tg_reception）
	tbl.attr( "rel", d.key );

	var name = defaultVal( d.nickname );
	var sex = defaultVal( d.sex );
	var age = defaultVal( d.age );

	tbl.find( "[rel='btnStudent']" ).attr( "rev", d.key );
	tbl.find( "tr:first th" ).html( "学员 [ " + name + " ] 的测评情况" );
	tbl.find( "[rel='student_info']" ).html( name + "，" + sex + "，" + age + " 岁" );
}

function defaultVal( val )
{
	if( empty( val ) )
		return "";
	return val;
}

//--------------------------------------------------------------------------
//
//	历史预约记录操作
//
//--------------------------------------------------------------------------

function empty_reserve()
{
	var tbl = $( "#tbl_reserve" );
	tbl.find( "tr:not(:first)" ).remove();
}

function nodata_reserve( msg )
{
	empty_reserve();
	var tbl = $( "#tbl_reserve" );
	tbl.append( '<tr><td width="75%" colspan="2">' + msg + '</td></tr>' );
}

function setReserveData( d )
{
	var h = '<tr>';
	h += '<th width="25%">预约时间</th>';
	h += '<td width="75%"><span class="stress unit hand" id="re_date"></span><span class="stress unit hand" id="re_time"></span></td>';
	h += '</tr>';
	h += '<tr>';
	h += '<th width="25%">预约中心</th>';
	h += '<td width="75%"><span class="stress unit hand" id="re_region"></span></td>';
	h += '</tr>';
	h += '<tr rel="hide">';
	h += '<th width="25%">预约状态</th>';
	h += '<td width="75%">当前状态：<span class="confirmed unit hand" id="re_state"></span></td>';
	h += '</tr>';
	h += '<tr>';
	h += '<th width="25%">短信通知';
	h += '<p class="caption">预约客户后的短信通知状态</p>';
	h += '</th>';
	h += '<td width="75%"><span class="stress unit hand" id="re_sms"></span></td>';
	h += '</tr>';
	h += '<tr>';
	h += '<th width="25%">预计需要时间</th>';
	h += '<td width="75%"><span class="stress unit hand" id="re_needtime"></span></td>';
	h += '</tr>';
	h += '<tr>';
	h += '<th width="25%" style="padding: 15px 10px 15px 10px;">其它备注情况</th>';
	h += '<td width="75%"><div id="re_remark">无</div></td>';
	h += '</tr>';

	var tbl = $( "#tbl_reserve" );
	tbl.append( h );
	update_row_bg();

	tbl.find( "tr:not(:first)" ).hide();

	// 赋值数据
	if( !empty( d ) )
	{
		reserveKey = d.key;

		tbl.find( "#re_date" ).html( d.date );
		tbl.find( "#re_time" ).html( d.time );

		if( d.gq )
		{
			tbl.find( "#re_date" ).parent()
					.append( '<span class="expired unit hand" id="expired">已过期</span>' );
		}

		tbl.find( "#re_region" ).html( d.regionns );
		tbl.find( "#re_state" ).html( state_ns( d.state ) );
		tbl.find( "#re_sms" ).html( d.sms == 1 ? "已发送短信" : "未发送短信" );
		tbl.find( "#re_needtime" ).html( d.needtime + " 小时" );
		tbl.find( "#re_remark" ).html( d.remark );
	}
	else
	{
		reserveKey = null;
	}
}

function state_ns( s )
{
	switch( parseInt( s ) ) {
		case 1:
			return '待确认';
		case 2:
			return '已出现';
		case 3:
			return '已过期';
		default:
			return '未知';
	}
}

/**
 * 点击预约记录的表头时，隐藏表体
 */
function name_row_click()
{
	var tbl = $( this ).parent().parent();
	var visible = tbl.find( "tr:not(:first)" ).visible();
	var trs = tbl.find( "tr:not(:first)" );

	if( visible )
	{
		trs.hide();
	}
	else
	{
		trs.show();
	}
}
//新增内容
function worth_form(){
	 var data = {};
	 data.key = $("#key").val();
     data.money = $("#money").val();
     data.moneyType = $("#moneyType").val();
     data.money1 = $("#money1").val();
     data.moneyType1 = $("#moneyType1").val();
	 data.rep_date1 = $("#rep_date1").val();
	 data.rep_date2 = $("#rep_date2").val();
	 data.worth = $( "#worth" ).val();
	 data.nestid = $("#nestid").val();
	 data.earnestType = $("#earnestType").val();
	 data.earnest_date = $("#earnest_date").val();
	 data.nest_date = $("#nest_date").val();
	 data.beizhu = $("#beizhu").val();
	 
	 data.all_words = $("#all_words").val();
	 data.all_words2 = $("#all_words2").val();
	 data.all_words3 = $("#all_words3").val();
	 
	 if(data.nestid!=null && data.nestid!=""){
		 if(data.all_words==""){
			 infopad.err( "请上传定金凭证。" );
			 return;
		 }
	 }
	 
	 if(data.money!=null && data.money!=""){
		 if(data.all_words2==""){
			 infopad.err( "请上传交款1凭证。" );
			 return;
		 }
	 }
	 
	 if(data.money1!=null && data.money1!=""){
		 if(data.all_words3==""){
			 infopad.err( "请上传交款2凭证。" );
			 return;
		 }
	 }
	 
	 var beginDate =  new Date(data.rep_date1.replace(/-/g,"/"));
	 var endDate = new Date(data.rep_date2.replace(/-/g,"/"));
	 if(beginDate!="" &&　endDate!=""){
	 	 if((endDate.getTime()-beginDate.getTime())>2592000000){
	 		alert("成交2时间比较成交1时间间隔小于30天");
	 		return;
		 }
	 }
	if(data.money>100000 || data.money1>100000){
		alert("金额超过10万，请重新核对是否有误！");
		return;
	}
if(window.confirm('保存后日期和金额将不可修改！')){
submitter.post( contextPath+"/index/consultant_client_reception_go.json", data, function( d ){
alert("保存成功！");
location.reload();		
}, "json" );
    return true;
 }else{
    return false;
}	
}

function check(d){
	var id = $("#"+d).attr("rel");
	if($("#"+id).is(':checked')){
		$("#student_test_list").find('#'+id).parent().show();
		$("#student_test_list").find('#'+id).show();
	}else if($("input[type='checkbox']").is(':checked')){
		$("#student_test_list").find('#'+id).css("display","none");
	}else{
		$("#student_test_list").find('table').css("display","none");
		$("#student_test_list").find('#'+id).parent().hide();
	}
}

function submit_form(){
	var data = {};
		// 客户key
		data.client = $("#clientkey").val();
		
		if(empty(data.client))
		{
			infopad.err( "未指定接待的目标客户。" );
			return;
		}

		data.key = $("#key").val();
		data.rkey = $("#reskey").val();
		data.rdate = $( "#rep_date" ).val();
		data.region = $( "#region" ).val();
		data.worth = $( "#worth" ).val();
		data.feature = $( "#rep_feature" ).val();
		data.reason = $("#reason").val();
		
		var student = {};
		$( "#student_test_list > table" ).each( function( idx )
		{
			var key = $( this ).attr( "id" );
			var data = student_data( $( this ) );
			if( data == false )
				return true;
			student[ key ] = data;
		} );
		data.student = JSON.stringify( student );

		submitter.post( contextPath+"/index/consultant_client_reception_go.json", data, function( d )
		{
			alert("保存成功！");
		}, "json" );
	}

	function student_data( tbl )
	{
		var data = {};
		data.key = tbl.attr( "id" );
		data.price = tbl.find("#price").val();
		data.moneylog = tbl.find("#moneylog").val();
		data.reason = tbl.find("#reason").val();
		data.remark = tbl.find("#remark").val();
		data.testuser = tbl.find( "#testusers" ).val();
		
		selects = [];
		tbl.find( "[rel='result'] > div" ).find( "p[rel^='TR_']" ).each( function( id )
		{
			var name = $( this ).attr( "rel" );
			var id = name.split( "_" )[ 1 ];
			var val = $( this ).find( ":radio:checked" ).val();
			var remark = $( this ).find( "input[name='TXT_" + id + "']" ).val();

			if( typeof ( val ) == 'undefined' )
			{
				val = 0;
			}

			if( !empty( remark ) )
			{
				remark = remark.replace( /,/ig, "，" );
				val = val + ":" + remark;
			}
			selects.push( val );
		} );
		data.result = selects.join( "," );
		return data;
	}

